package com.jhj.common.util;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Cookie工具类，提供cookie的添加，删除和查询
 * 
 * @author GuoBing
 */
public class JhjCookieUtil {
    
    /**
     * 添加cookie到指定路径，设置生存时间
     * 
     * @param name
     * @param value
     * @param age
     * @param path
     * @param domain
     * @param response
     */
    public static void addCookie(String name, String value, int age, String path, String domain, HttpServletResponse response) {
        try {
            String valAscii = URLEncoder.encode(value, "utf-8");
            Cookie cookie = new Cookie(name, valAscii);
            cookie.setMaxAge(age);
            if (path != null) {
                cookie.setPath(path);
            }
            
            if (domain != null) {
                cookie.setDomain(domain);
            }
            
            response.addCookie(cookie);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        
    }
    
    /**
     * 获取指定名称的Cookie值
     * 
     * @param name
     * @param request
     * @return
     */
    public static String getValue(String name, HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (cookies == null) {
            return null;
        }
        String value = null;
        for (Cookie c : cookies) {
            if (c.getName().equals(name)) {
                try {
                    value = URLDecoder.decode(c.getValue(), "utf-8");
                    break;
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        }
        return value;
    }
    
    /**
     * 删除指定路径下的指定名字的Cookie
     * 
     * @param name cookie名称
     * @param path cookie路径
     * @param domain 域
     * @param response
     */
    public static void removeCookie(String name, String path, String domain, HttpServletResponse response) {
        Cookie c = new Cookie(name, "");
        c.setMaxAge(0);
        
        if (path != null) {
            c.setPath(path);
        }
        
        if (domain != null) {
            c.setDomain(domain);
        }
        
        response.addCookie(c);
    }
    
    /**
     * 删除当前路径下的指定名字的Cookie
     * 
     * @param name cookie名称
     * @param response
     */
    public static void removeCookie(String name, HttpServletResponse response) {
        removeCookie(name, null, null, response);
    }
    
}
